package com.beemans.corekit.integration.metrics;

import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.json.JSONArray;
import org.json.JSONObject;

public final class MetricsCache {

    /**
     * @return 获取地区
     */
    public static String getLocale() {
        return MetricsSpUtils.getInstance().getString(MetricsConstant.CACHE_LOCALE, null);
    }

    public static void updateLocale(@NonNull String value) {
        MetricsSpUtils.getInstance().putString(MetricsConstant.CACHE_LOCALE, value);
    }

    /**
     * 获取设备唯一标识码
     */
    @Nullable
    public static String getDeviceId() {
        return MetricsSpUtils.getInstance().getString(MetricsConstant.CACHE_GUID, null);
    }

    /**
     * 更新设备唯一标识码
     */
    public static void updateDeviceId(@NonNull String value) {
        MetricsSpUtils.getInstance().putString(MetricsConstant.CACHE_GUID, value);
    }

    /**
     * 是否上报 Referrer
     */
    public static boolean isReportReferrer() {
        final boolean canReport = MetricsSpUtils.getInstance().getBoolean(MetricsConstant.CACHE_REFERRER, true);
        if (canReport) {
            MetricsSpUtils.getInstance().putBoolean(MetricsConstant.CACHE_REFERRER, false);
        }
        return canReport;
    }

    /**
     * 是否上报 UA
     */
    public static boolean isReportUA() {
        final boolean canReport = MetricsSpUtils.getInstance().getBoolean(MetricsConstant.CACHE_UA, true);
        if (canReport) {
            MetricsSpUtils.getInstance().putBoolean(MetricsConstant.CACHE_UA, false);
        }
        return canReport;
    }

    public static void updateItemInfos(@NonNull JSONArray jsonArray) {
        final String json = jsonArray.toString();

        // 检查数据大小，避免 SharedPreferences 存储过大数据
        if (json.length() > MetricsConstant.CACHE_MAX_SIZE_BYTES) {
            // 数据过大时，优先保留旧的数据
            final JSONArray limitedArray = limitArraySize(jsonArray);
            final String limitedJson = limitedArray.toString();
            MetricsSpUtils.getInstance().putString(MetricsConstant.CACHE_INFO, limitedJson);
        } else {
            MetricsSpUtils.getInstance().putString(MetricsConstant.CACHE_INFO, json);
        }
    }

    /**
     * 限制数组大小，优先保留旧的数据
     */
    @NonNull
    private static JSONArray limitArraySize(@NonNull JSONArray original) {
        final JSONArray limited = new JSONArray();
        try {
            // 从前往后添加，优先保留旧的数据
            for (int i = 0; i < original.length(); i++) {
                final JSONObject obj = original.optJSONObject(i);
                if (obj == null) {
                    continue;
                }
                limited.put(obj);

                if (limited.toString().length() > MetricsConstant.CACHE_MAX_SIZE_BYTES) {
                    // 超过限制，移除最后添加的对象并停止
                    limited.remove(limited.length() - 1);
                    break;
                }
            }
        } catch (Exception ignored) {
        }
        return limited;
    }

    @NonNull
    public static JSONArray getItemInfos() {
        final String json = MetricsSpUtils.getInstance().getString(MetricsConstant.CACHE_INFO, null);
        if (TextUtils.isEmpty(json)) {
            return new JSONArray();
        }
        try {
            return new JSONArray(json);
        } catch (Throwable e) {
            return new JSONArray();
        }
    }

    public static void clearItemInfos() {
        MetricsSpUtils.getInstance().putString(MetricsConstant.CACHE_INFO, null);
    }

    /**
     * 更新正在上报的数据缓存
     */
    public static void updateReportingInfos(@NonNull JSONArray jsonArray) {
        final String json = jsonArray.toString();
        MetricsSpUtils.getInstance().putString(MetricsConstant.CACHE_REPORTING_INFO, json);
    }

    /**
     * 获取正在上报的数据缓存
     */
    @NonNull
    public static JSONArray getReportingInfos() {
        final String json = MetricsSpUtils.getInstance().getString(MetricsConstant.CACHE_REPORTING_INFO, null);
        if (TextUtils.isEmpty(json)) {
            return new JSONArray();
        }
        try {
            return new JSONArray(json);
        } catch (Throwable e) {
            return new JSONArray();
        }
    }

    /**
     * 清空正在上报的数据缓存
     */
    public static void clearReportingInfos() {
        MetricsSpUtils.getInstance().putString(MetricsConstant.CACHE_REPORTING_INFO, null);
    }
}
